﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Admin_Web_test
{
    public class ErrorExceptionFilter : IExceptionFilter
    {
        private readonly Common.DBHelp.MySqlContext _context;

        public ErrorExceptionFilter(Common.DBHelp.MySqlContext context)
        {
            //https://www.cnblogs.com/yaopengfei/p/12194230.html   5.6
            context.ChangeTracker.QueryTrackingBehavior = Microsoft.EntityFrameworkCore.QueryTrackingBehavior.NoTracking;
            //关闭状态同步
            context.ChangeTracker.AutoDetectChangesEnabled = false;
            //开启：context.ChangeTracker.DetectChanges();
            _context = context;
        }
        public void OnException(ExceptionContext context)
        {
            string controllerName = context.RouteData.Values["controller"].ToString();
            string actionName = context.RouteData.Values["action"].ToString();
            string ex = context.Exception.Message;
            Error e = new Error();
            e.Msg = $"控制器：{controllerName}方法：{actionName}错误：{ex}";
            _context.Error.Add(e);
            _context.SaveChanges();
            context.Result = new RedirectResult("/error/index");
            context.ExceptionHandled = true;   //最后需要把错误处理完成改为true，不然会进两次这方法。
        }
    }
}
